import BaseService from './base';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;

export default class CustomerService extends BaseService {
  constructor({ customerDao }) {
    super();
    this.customerDao = customerDao
  }

  async getCustomerAll (customer) {
    const [err, list] = await this.customerDao.getCustomerAll({
      attributes: ['PASSENGER_LASTNAME', 'PASSENGER_FIRSTNAME', 'PASSENGER_PASSPORT'],
      where: {
        mark: customer.mark
      }
    });
    if (err) {
      return this.fail('获取列表失败', null, err);
    }
    return this.success('查询成功', list);
  }

  async getCustomerList(customer) {
    const [err, count, rows] = await this.customerDao.getCustomerList({
      where: {
        PASSENGER_PASSPORT: customer.PASSENGER_PASSPORT === '' ? {
          [Op.ne]: null
        } : customer.PASSENGER_PASSPORT,
        mark: customer.mark
      },
      limit: customer.limit,
      offset: customer.limit * (customer.offset - 1),
      distinct: true
    });
    if (err) {
      return this.fail('获取列表失败', null, err);
    }
    return this.success('查询成功', count, rows);
  }

  async addCustomer(customer) {
    const [exsitErr, itemExsit] = await this.customerDao.findOne({
      where: {
        PASSENGER_PASSPORT: customer.PASSENGER_PASSPORT
      }
    });
    if (exsitErr) {
      return this.fail('添加失败', null, exsitErr);
    }
    if (itemExsit) {
      return this.fail('已存在');
    }
    const [addErr] = await this.customerDao.addCustomer(customer);
    if (addErr) {
      return this.fail('添加失败', null, addErr);
    }
    return this.success('添加成功')
  }

  async delCustomer(customer) {
    const [err, updateCustomer] = await this.customerDao.update(customer, {
      where: {
        id: customer.id
      }
    });
    if (err) {
      return this.fail('删除失败');
    }
    return this.success('删除成功');
  }

  async updateCustomer(customer) {
    const [err, updateCustomer] = await this.customerDao.update(customer, {
      where: {
        id: customer.id
      }
    });
    if (err) {
      return this.fail('更新失败');
    }
    return this.success('更新成功');
  }
}